import axios from 'axios'
import fs from 'fs'
import path from 'path'

// 配置部分
const GITLAB_URL = 'https://gitlab.influx.io' // 替换为你的GitLab实例URL
const PRIVATE_TOKEN = 'vyrFEDFoi6sA6_uNegpX' // 替换为你的Personal Access Token
const PROJECT_ID = 61 // 替换为你的项目ID
const OUTPUT_FILE = 'jobs.json'

// 设置请求头
const headers = {
  'PRIVATE-TOKEN': PRIVATE_TOKEN
}

const url = `${GITLAB_URL}/api/v4/projects/${PROJECT_ID}/jobs?per_page=100`

// 获取指定项目的所有作业
async function getJobs(url) {
  const response = await axios.get(url, { headers })
  const jobs = response.data
  //   console.log(response.headers.link)
  //   fs.writeFileSync(OUTPUT_FILE, JSON.stringify(jobs))
  const nextUrl = response.headers.link.match(/<(.+)>; rel="next"/)[1]
  // 删除job
  try {
    for (const job of jobs) {
      const status = await deleteArtifacts(job.id)
      console.log(job.id, status)

      if (!status) continue
    }
    getJobs(nextUrl)
  } catch (error) {
    console.error('Error deleting artifacts:', error)
  }
}

// 删除指定作业的Artifacts
async function deleteArtifacts(jobId) {
  const url = `${GITLAB_URL}/api/v4/projects/${PROJECT_ID}/jobs/${jobId}/erase`
  try {
    await axios.post(url, null, { headers })
    return true
  } catch (err) {
    console.log(err)
    return false
  }
}

// 主函数
// async function main() {
//   try {
//     const jobs = await getJobs()
//     for (const job of jobs) {
//       await deleteArtifacts(job.id);
//     }
//     console.log(jobs)
//   } catch (error) {
//     console.error('Error deleting artifacts:', error)
//   }
// }

getJobs(url)
